/***********************************************************
 * author: wuzhong
 * create: 2022-09-05
 * email：419479707@qq.com
 * source:
 * board:esp8266 core for arduino v3.0.2
 ***********************************************************/

#include "Helper.h"

long lastMqttConn;     // 上次mqtt连接时间
long lastDataMonitor;  // 上次定时发布温湿度数据

/**
 * 启动
 */
void setup()
{
  //设置内置LED引脚为输出模式以便控制LED,同时控制继电器
  pinMode(RELAYPIN, OUTPUT); 
  // 将引脚输出初始化为高，因为继电器是低电平触发
  digitalWrite(RELAYPIN, HIGH);  
  //打开串行端口：
  Serial.begin(115200);
  printMsg("bihua smart device starting...");
  connectWifi();
  createWebServer();
}
/**
 * 循环执行
 */
void loop()
{
  // Wifi掉线重连
  if (WiFi.status() != WL_CONNECTED)
  {
    connectWifi();
  }
  // 检查http服务器访问
  server.handleClient();
  // 非阻塞Mqtt重连，间隔30秒
  if (mqttOpen == 1 && WiFi.status() == WL_CONNECTED)
  {
    long now = millis();
    if (!mqttClient.connected())
    {
      if (now - lastMqttConn > 30000)
      {
        lastMqttConn = now;
        connectMqtt();
        mqttClient.subscribe(deviceCommandTopic);
      }
    }
    else
    {
      mqttClient.loop();
    }
  }
}
